package com.qqtech.qquan.user.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.community.model.CommunityBaseVo;
import com.qqtech.qquan.community.service.CommunityBaseService;
import com.qqtech.qquan.sys.controller.BaseAdminController;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.enums.SysRoleStatusDictEnum;
import com.qqtech.qquan.sys.model.SysMenuQuery;
import com.qqtech.qquan.sys.model.SysMenuVo;
import com.qqtech.qquan.sys.model.SysRole;
import com.qqtech.qquan.sys.model.SysRoleVo;
import com.qqtech.qquan.sys.service.SysMenuService;
import com.qqtech.qquan.sys.service.SysRoleService;
import com.qqtech.qquan.user.model.UserAdmin;
import com.qqtech.qquan.user.model.UserAdminQuery;
import com.qqtech.qquan.user.model.UserAdminVo;
import com.qqtech.qquan.user.service.UserAdminService;

@Controller
@RequestMapping(value = "/user/admin")
public class UserAdminController extends BaseAdminController {
	public static final Logger log = LoggerFactory.getLogger(UserAdminController.class);

	private Font mFont = new Font("Arial Black", Font.PLAIN, 18);
	@Resource
	private UserAdminService userAdminService;
	@Resource
	private SysRoleService sysRoleService;
	@Resource
	private SysMenuService sysMenuService;
	
	@Resource
	private CommunityBaseService communityBaseService;

	@Override
	protected BaseService<UserAdmin> getBaseService() {
		return userAdminService;
	}

	/**
	 * 登录页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/login";
	}

	/**
	 * 登录提交
	 * 
	 * @param req
	 * @param userLogin
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Result login(UserAdminQuery userAdmin, HttpServletRequest req) {
		Result ret = new Result();
		if (userAdmin == null) {
			ret.addErr("参数不能为空");
		} else {
			if (StringUtil.isBlank(userAdmin.getName())) {
				ret.addErr("用户名/手机不能为空");
			}
			if (StringUtil.isBlank(userAdmin.getPassword())) {
				ret.addErr("密码不能为空");
			}
			if (StringUtil.isBlank(userAdmin.getVerifyCode())) {
				ret.addErr("验证码不能为空");
			} else {
				String verifyCode = (String) req.getSession().getAttribute(SysConst.ADMIN_LOGIN_VERIFYCODE);
				if (null == verifyCode || !userAdmin.getVerifyCode().toLowerCase().equals(verifyCode.toLowerCase())) {
					ret.addErr("验证码错误");
				}
			}
		}
		if (ret.checkForm()) {
			userAdmin.setPassword(StringUtil.shaEncode(userAdmin.getPassword()));
			List<UserAdmin> adminList = userAdminService.queryList(userAdmin);
			if (adminList == null || adminList.size() == 0) {
				ret.addErr("账号和密码不匹配");
			} else {
				UserAdmin tempUser = adminList.get(0);
				if (tempUser.getCommunityId() != null && tempUser.getCommunityId().intValue() != 0) {
					ret.addErr("请您登录社区管理后台");
					return ret;
				} else {
					req.getSession().setAttribute(SysConst.ADMIN_USER_SESSION, tempUser);
					req.getSession().removeAttribute(SysConst.ADMIN_LOGIN_VERIFYCODE);
					ret.getMap().put("user", userAdminService.getById(tempUser.getId()));
					ret.setMsg("/user/admin/main"); // 成功后跳到
				}
			}
		}
		return ret;
	}

	/**
	 * 主界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/main", method = RequestMethod.GET)
	public String main(Model model, HttpServletRequest request, HttpServletResponse response) {
		UserAdmin login = super.getLoginUser(); // 获取登录用户
		UserAdmin user = userAdminService.getById(login.getId());
		List<SysMenuVo> menus = null;
		SysRole roleAdmin = new SysRole();
		roleAdmin.setName(SysConst.SYS_ROLE_ADMIN_NAME);
		roleAdmin.setStatus(SysRoleStatusDictEnum.ENABLE.getCode());
		List<SysRole> roleAdminList = sysRoleService.queryList(roleAdmin);
		if (roleAdminList != null && roleAdminList.size() > 0) {
			roleAdmin = roleAdminList.get(0);
		}

		List<SysRole> roles = sysRoleService.queryListByUserId(user.getId()); // 得到角色
		menus = sysMenuService.queryListByParentId(null);
		Boolean isAdmin = false;
		for (SysRole role : roles) {
			if (SysConst.SYS_ROLE_ADMIN_NAME.equals(role.getName())) {
				isAdmin = true;
			}
		}
		if (isAdmin) { // 总管理员
			menus = sysMenuService.queryListByParentId(null);
		} else {
			List<Integer> roleIdList = new ArrayList<Integer>(roles.size());
			for (SysRole r : roles) {
				roleIdList.add(r.getId());
			}
			SysMenuQuery sysMenuQuery = new SysMenuQuery();
			sysMenuQuery.setRoleIdList(roleIdList);
			menus = sysMenuService.topMenuForRole(sysMenuQuery);
		}
		model.addAttribute("loginUser", roleAdmin);
		model.addAttribute("menus", menus);
		return "/main";
	}

	/**
	 * 默认界面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/default", method = RequestMethod.GET)
	public String defaulted() {
		return "/default";
	}

	/**
	 * 退出
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest req) {
		req.getSession().removeAttribute(SysConst.ADMIN_USER_SESSION);
		return "/login";
	}

	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/user/admin/user-list";
	}

	/**
	 * 列表页面数据
	 * 
	 * @param userDomain
	 *            查询条件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage doList(UserAdminQuery user, HttpServletRequest request, HttpServletResponse response) {
		// super.getLoginUser(request, response);
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		user.setSize(Integer.valueOf(rows));
		Pageable pageKit = new PageKit(user.getPage(), user.getSize(), new PageOrder(Direction.ASC, "id"));
		Page<UserAdminVo> page = userAdminService.queryPageList(user, pageKit);
		CommunityBaseVo community = null;
		for(UserAdminVo admin : page){
			if(admin.getCommunityId()!=null){
				community = communityBaseService.getById(admin.getCommunityId());
				if(community!=null){
					admin.setCommunityName(community.getName());
				}
			}
		}
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	/**
	 * 添加页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add() {
		return "/user/admin/user-add";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(UserAdminVo user, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		if (StringUtils.isBlank(user.getName())) {
			ret.addErr("名称不能为空");
		} else {
			UserAdmin testUser = new UserAdmin();
			testUser.setName(user.getName());
			Integer count = userAdminService.queryCount(testUser);
			if (count > 0) {
				ret.addErr("此用户名已被注册");
			}
		}
		if (StringUtils.isBlank(user.getPassword())) {
			ret.addErr("密码不能为空");
		}
		if (ret.checkForm()) {
			user.setPassword(StringUtil.shaEncode(user.getPassword()));
			int userId = userAdminService.insert(user);
			if (userId != 0) {
				user.setId(userId);
			}
			user.setPassword(null);
		}
		return ret;
	}

	@RequestMapping(value = "/addRole/{userId}", method = RequestMethod.GET)
	public String addRole(@PathVariable Integer userId, HttpServletRequest request, HttpServletResponse response) {
		request.setAttribute("userId", userId);
		return "/user/admin/user-addRole";
	}

	@RequestMapping(value = "/addRole/{userId}", method = RequestMethod.POST)
	@ResponseBody
	public Result addRole(@PathVariable Integer userId, UserAdminVo param) {
		UserAdmin user = userAdminService.getById(userId);
		Result ret = new Result();
		if (user == null) {
			ret.addErr("用户不存在");
		}
		if (ret.checkForm()) {
			sysRoleService.saveRoleAndUser(param);
		}
		return ret;
	}

	@RequestMapping(value = "/roletree/{userId}", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public void roleTree(@PathVariable Integer userId, HttpServletResponse response) {
		SysRoleVo sysRole = new SysRoleVo();
		sysRole.setStatus(SysRoleStatusDictEnum.ENABLE.getCode());
		List<SysRoleVo> roles = sysRoleService.queryList(sysRole);
		List<SysRole> selectedRoles = Collections.emptyList();
		if (userId != null) {
			selectedRoles = sysRoleService.queryListByUserId(userId);
		}
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>(roles.size());
		for (SysRoleVo r : roles) {
			Map<Object, Object> node = new HashMap<Object, Object>();
			node.put("id", r.getId());
			node.put("text", r.getName());
			// node.put("checked", selectedRoles.contains(r));
			if (selectedRoles != null && selectedRoles.size() > 0) {
				for (SysRole selectRole : selectedRoles) {
					if (selectRole.getId().equals(r.getId())) {
						node.put("checked", true);
					}
				}
			}
			node.put("iconCls", "icon-star");
			tree.add(node);
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/verify", method = RequestMethod.GET)
	public void verify(OutputStream os, HttpServletRequest request, HttpServletResponse response, Model model)
			throws IOException {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");

		int width = 75, height = 30;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(1, 1, width - 1, height - 2);
		g.setColor(new Color(102, 102, 102));
		g.drawRect(0, 0, width - 1, height - 2);
		g.setFont(mFont);
		g.setColor(getRandColor(160, 200));
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g.drawLine(x, y, x + xl, y + yl);
		}

		for (int i = 0; i < 70; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(12) + 1;
			int yl = random.nextInt(6) + 1;
			g.drawLine(x, y, x - xl, y - yl);
		}

		String sRand = "";
		for (int i = 0; i < 4; i++) {
			String tmp = getRandomChar();
			sRand += tmp;
			g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(tmp, 15 * i + 10, 20);
		}
		request.getSession().setAttribute(SysConst.ADMIN_LOGIN_VERIFYCODE, sRand);
		model.addAttribute(SysConst.ADMIN_LOGIN_VERIFYCODE, sRand);
		g.dispose();
		ImageIO.write(image, "JPEG", os);
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private String getRandomChar() {
		int rand = (int) Math.round(Math.random() * 2);
		long itmp = 0;
		char ctmp = '\\';
		switch (rand) {
		case 1:
			itmp = Math.round(Math.random() * 25 + 65);
			ctmp = (char) itmp;
			return String.valueOf(ctmp);
		case 2:
			itmp = Math.round(Math.random() * 25 + 97);
			ctmp = (char) itmp;
			return String.valueOf(ctmp);
		default:
			itmp = Math.round(Math.random() * 9);
			return String.valueOf(itmp);
		}
	}

	/**
	 * 后台权限不够,拒绝访问页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/accessDenied", method = RequestMethod.GET)
	public String accessDenied() {
		return "access_denied";
	}
}
